import { UserItem, UserList, deleteUser } from '@/services/user/user';
import { PlusOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { ActionType, ProTable } from '@ant-design/pro-components';
import { Button, Popconfirm, message } from 'antd';
import type { SortOrder } from 'antd/es/table/interface';
import { useRef, useState } from 'react';
import UserModal from './components/UserModal';

export default function User() {
  const [modalVisible, setModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<UserItem | undefined>();
  const actionRef = useRef<ActionType>();

  const handleModalVisible = (visible: boolean) => {
    setModalVisible(visible);
    if (!visible) {
      setCurrentRecord(undefined);
    }
  };

  const handleDelete = async (id: number) => {
    try {
      const res = await deleteUser(id);
      if (res.success) {
        message.success('删除成功');
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const columns: ProColumns<UserItem>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      ellipsis: true,
    },
    {
      title: '地址',
      dataIndex: 'adress',
      ellipsis: true,
    },
    {
      title: '角色',
      dataIndex: 'role',
      valueType: 'select',
      valueEnum: {
        admin: { text: '管理员', status: 'Success' },
        user: { text: '普通用户', status: 'Default' },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        active: { text: '正常', status: 'Success' },
        inactive: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '最后登录时间',
      dataIndex: 'lastLoginTime',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRecord(record);
            setModalVisible(true);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title="确定要删除这个用户吗？"
          onConfirm={() => handleDelete(record.id)}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <>
      <ProTable<UserItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (
          params,
          sort: Record<string, SortOrder>,
          filter: Record<string, (string | number)[] | null>,
        ) => {
          try {
            const { current, pageSize, ...restParams } = params;
            const sortField = Object.keys(sort)[0];
            const sortOrder = sort[sortField];

            const { data, success } = await UserList({
              current,
              pageSize,
              ...restParams,
              sortField: sortField,
              sortOrder: sortOrder,
              ...filter,
            });

            return {
              data: data.user,
              success,
              total: data.total,
            };
          } catch (error) {
            message.error('获取用户列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: true,
          optionRender: (searchConfig, formProps, dom) => [...dom.reverse()],
        }}
        form={{
          syncToUrl: false,
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        headerTitle="用户列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setCurrentRecord(undefined);
              handleModalVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
      />
      <UserModal
        visible={modalVisible}
        onVisibleChange={handleModalVisible}
        initialValues={currentRecord}
        onSuccess={() => {
          handleModalVisible(false);
          actionRef.current?.reload();
        }}
      />
    </>
  );
}